package com.ftf.tp.blog.infrastructure.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.ftf.tp.common.security.properties.TpCloudSecurityProperties;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * es配置
 *
 * @author tanghao
 */
@Configuration
@EnableConfigurationProperties(ElasticsearchParams.class)
@ConditionalOnProperty("elasticsearch.address")
public class ElasticsearchConfig {

    @Resource
    private ElasticsearchParams elasticsearchParams;


    @Bean
    public ElasticsearchClient elasticsearchClient() {
        //es地址，以逗号分隔
        String nodes = elasticsearchParams.getAddress();
        nodes = nodes.contains("http://") ? nodes.replace("http://", "") : nodes;
        String scheme = elasticsearchParams.getScheme();
        List<HttpHost> httpHostList = new ArrayList<>();
        //拆分es地址
        for (String address : nodes.split(",")) {
            int index = address.lastIndexOf(":");
            httpHostList.add(new HttpHost(address.substring(0, index), Integer.parseInt(address.substring(index + 1)), scheme));
        }
        //密码配置
//        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
//                elasticsearchParams.getUserName(), elasticsearchParams.getPassword()));
        //转换成 HttpHost 数组
        HttpHost[] httpHosts = httpHostList.toArray(new HttpHost[0]);

        //构建连接对象
        RestClientBuilder builder = RestClient.builder(httpHosts);

        // 异步连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(elasticsearchParams.getConnectTimeout());
            requestConfigBuilder.setSocketTimeout(elasticsearchParams.getSocketTimeout());
            requestConfigBuilder.setConnectionRequestTimeout(elasticsearchParams.getConnectionRequestTimeout());
            return requestConfigBuilder;
        });

        // 异步连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(elasticsearchParams.getMaxConnectNum());
            httpClientBuilder.setMaxConnPerRoute(elasticsearchParams.getMaxConnectPerRoute());
//            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            return httpClientBuilder;
        });

        ElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }


    /**
     * 当前es相关的配置存在则实例化RestHighLevelClient,如果不存在则不实例化RestHighLevelClient
     */
    @Bean
    public ElasticsearchAsyncClient elasticsearchAsyncClient() {

        //es地址，以逗号分隔
        String nodes = elasticsearchParams.getAddress();
        nodes = nodes.contains("http://") ? nodes.replace("http://", "") : nodes;
        String scheme = elasticsearchParams.getScheme();
        List<HttpHost> httpHostList = new ArrayList<>();
        //拆分es地址
        for (String address : nodes.split(",")) {
            int index = address.lastIndexOf(":");
            httpHostList.add(new HttpHost(address.substring(0, index), Integer.parseInt(address.substring(index + 1)), scheme));
        }
        //es密码
//        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
//                elasticsearchParams.getUserName(), elasticsearchParams.getPassword()));
        //转换成 HttpHost 数组
        HttpHost[] httpHosts = httpHostList.toArray(new HttpHost[0]);

        //构建连接对象
        RestClientBuilder builder = RestClient.builder(httpHosts);

        // 异步连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(elasticsearchParams.getConnectTimeout());
            requestConfigBuilder.setSocketTimeout(elasticsearchParams.getSocketTimeout());
            requestConfigBuilder.setConnectionRequestTimeout(elasticsearchParams.getConnectionRequestTimeout());
            return requestConfigBuilder;
        });

        // 异步连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(elasticsearchParams.getMaxConnectNum());
            httpClientBuilder.setMaxConnPerRoute(elasticsearchParams.getMaxConnectPerRoute());
//            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            httpClientBuilder.disableAuthCaching();
            return httpClientBuilder;
        });

        ElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());
        return new ElasticsearchAsyncClient(transport);
    }

}


